﻿using Microsoft.Practices.Unity;
using DoNet.Common.Cache;

namespace DoNet.Common.IoC
{
    public sealed class UnityContext
    {
        //private IUnityContainerStorage _storage;
        private ICacheStrategy _cache;
        private static readonly object _lockObject = new object();
        private static UnityContext _current;

        private UnityContext()
        {
            //_storage = new WebUnityContainerStorage();
            _cache = new WebCaching();
        }

        /// <summary>
        /// 单例方式实例化
        /// </summary>
        public static UnityContext Current
        {
            get
            {
                if (_current == null)
                {
                    lock (_lockObject)
                    {
                        if (_current == null)
                        {
                            _current = new UnityContext();
                        }
                    }
                }
                return _current;
            }
        }

        /// <summary>
        /// Unity的IoC容器对象 (存放在HttpContext.Current.Application中)
        /// </summary>
        public IUnityContainer Container
        {
            get
            {
                //IUnityContainer container = _storage.Get();
                IUnityContainer container = _cache.GetCache("container") as IUnityContainer;
                if (container == null)
                {
                    container = new UnityContainerBuilder().BuilderUnityContainer();
                    _cache.SetCache("container", container);
                    //_storage.Set(container);
                }

                return container;
            }
        }

        //public void SetStorage(IUnityContainerStorage storage)
        //{
        //    _storage = storage;
        //}

        //public void SetStorage<TStorage>() where TStorage : IUnityContainerStorage, new()
        //{
        //    _storage = new TStorage();
        //}
    }
}
